#pragma once

#include "index.hpp"
#include <algorithm>
#include <jsoncpp/json/json.h>

namespace ns_searcher
{
    class Searcher
    {
    public:
        Searcher() {}
        ~Searcher() {}

    public:
        void InitSearcher(const std::string &input)
        {
            // 1. 获取或者创建index对象
            index = ns_index::Index::GetInstance();
            std::cout << "获取单例成功" << std::endl;
            // 2. 根据index对象建立索引
            index->BuildIndex(input);
            std::cout << "建立索引成功" << std::endl;
        }

        // query: 搜索关键字
        // json_string: 返回给用户浏览器的数据(搜索结果)
        void Search(const std::string &query, std::string *json_string)
        {
            // 1. 对query进行分词
            std::vector<std::string> words;
            ns_util::JiebaUtill::CutString(query, &words);
            // 2. 根据分词后的结果进行查早
            ns_index::InvertedList inverted_list_all;
            for (auto &word : words)
            {
                boost::to_lower(word);
                ns_index::InvertedList *inverted_list = index->GetInvertedList(word);
                if (inverted_list == nullptr)
                {
                    continue;
                }
                inverted_list_all.insert(inverted_list_all.end(), inverted_list->begin(), inverted_list->end());
            }
            // 3. 汇总查早结果, 按照相关性进行降序排序
            sort(inverted_list_all.begin(), inverted_list_all.end(),
                 [](const ns_index::InvertedElem &e1, const ns_index::InvertedElem &e2)
                 {
                     return e1.weight > e2.weight;
                 });
            // 4. 构建json串
            Json::Value root;
            for (auto &item : inverted_list_all)
            {
                ns_index::DocInfo *doc = index->GetForWardIndex(item.doc_id);
                if (doc == nullptr)
                {
                    continue;
                }

                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content, item.word);
                elem["url"] = doc->url;

                // debug
                elem["ID"] = doc->doc_id;
                elem["weight"] = item.weight;

                root.append(elem);
            }
            Json::StyledWriter writer;
            *json_string = writer.write(root);
        }

        // 获取摘要
        std::string GetDesc(const std::string &html_content, const std::string &word)
        {
            // 思路: 找到word在html中首次出现的位置, 然后截取前50后50字节，如果前后不到100字节就直接有多少截取多少

            const int prev_step = 50;
            const int next_step = 100;

            // 1. 寻找首次出现的位置
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(),
                                    [](int x, int y)
                                    {
                                        return std::tolower(x) == std::tolower(y);
                                    });
            if (iter == html_content.end())
            {
                return "NONE1!";
            }
            int pos = std::distance(html_content.begin(), iter);

            // 2. 获取start和end
            int start = 0;
            int end = html_content.size() - 1;
            if (pos > start + prev_step)
                start = pos - prev_step;
            if (pos < end - next_step)
                end = pos + next_step;

            // 3. 截取字符串
            if (start >= end)
                return "NONE2!"; // 这个情况不可能出现
            return html_content.substr(start, end - start);
        }

    private:
        ns_index::Index *index; // 提供系统查找的索引
    };
};